package com.google.code.wifimaps.core.xmlparser;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.google.code.wifimaps.entidade.WifiNetwork;


public class AiroSystemOutContentHandler extends DefaultHandler{
	
	private List<WifiNetwork> wifiList;
	private WifiNetwork wifiNetwork;
	private String tempVal;

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		tempVal = new String(ch, start, length);
	}

	@Override
	public void endDocument() throws SAXException {
	}

	@Override
	public void endElement(String uri, String localName, String name)
			throws SAXException {
		if(name.equals("AP")){
			wifiList.add(wifiNetwork);
		} else if (name.equals("WEP")){
			wifiNetwork.setWep(tempVal);
		} else if (name.equals("MAC")){
			wifiNetwork.setMacAddress(tempVal);
		} else if (name.equals("SSID")){
			wifiNetwork.setSsid(tempVal);
		} else if (name.equals("Type")){
			wifiNetwork.setType(tempVal);
		} else if (name.equals("RSSI")){
			wifiNetwork.setRssi(new Integer(tempVal));
		} else if (name.equals("MaxRSSI")){
			wifiNetwork.setMaxRssi(new Integer(tempVal));
		} else if (name.equals("MinRSSI")){
			wifiNetwork.setMinRssi(new Integer(tempVal));
		} else if (name.equals("Channel")){
			wifiNetwork.setChannel(new Integer(tempVal));
		} else if (name.equals("LastSeen")){
			try {
				wifiNetwork.setLastSeen(this.convertDate(tempVal));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		} else if (name.equals("MAC")){
			wifiNetwork.setMacAddress(tempVal);
		} else if (name.equals("HDOP")){
			wifiNetwork.setHdop(new Integer(tempVal));
		} else if (name.equals("Lat")){
			wifiNetwork.setLatPosition(new BigDecimal(tempVal));
		} else if (name.equals("Lon")){
			wifiNetwork.setLonPosition(new BigDecimal(tempVal));
		}
	}

	@Override
	public void startDocument() throws SAXException {
		 wifiList = new ArrayList<WifiNetwork>();
	}

	@Override
	public void startElement(String uri, String localName, String name,
			Attributes attributes) throws SAXException {
		if(name.equals("AP")){
			wifiNetwork = new WifiNetwork();
		}
	}
	
	private Date convertDate(String strDate) throws ParseException{
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
		strDate = strDate.substring(0,22)+strDate.substring(22+1);
		return (Date) df.parse(strDate);
	}

	public List<WifiNetwork> getWifiList() {
		return wifiList;
	}

}
